package com.sleep.statemachine.config;

import com.sleep.statemachine.domain.Events;
import com.sleep.statemachine.domain.States;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

@Configuration
@EnableStateMachine(name = "OrderStateMachine")
@Slf4j
public class OrderStateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> {
    // 定义初试状态
    @Override
    public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception {
        states.withStates()
                .initial(States.UNPAID)  //设置初始化状态
                .states(EnumSet.allOf(States.class)); // 设置状态集合
    }

    // 状态装换过程  触发什么事件就转换到什么状态
    @Override
    public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception {
        transitions.withExternal() // 添加外部事件
                .source(States.UNPAID).target(States.WAITING_FOR_RECEIVE) //原状态到目标状态
                .event(Events.PAY).and() // 触发事件
                .withExternal()
                .source(States.WAITING_FOR_RECEIVE).target(States.DONE)
                .event(Events.RECEIVE);
    }
}
